from django.http import HttpResponse, JsonResponse
import jira
from jira import JIRA
import pymysql
import datetime
from . import config
import os
import os
import json
from django.core.files.storage import default_storage
from . import config

def up_file(request):
    save_path='/tmp'
    if request.method == 'POST' and request.FILES.get('file'):
        try:
            myfile = request.FILES['file']
            base_dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            path=os.path.join(base_dir,save_path.lstrip('/'))
            print (path)
            if not os.path.exists(path):
                os.makedirs(path)
            path=os.path.join(base_dir,save_path.lstrip('/'),myfile.name)
            with default_storage.open(path, 'wb+') as destination:
                for chunk in myfile.chunks():
                    destination.write(chunk)
            data={'msg':'上传成功'}
        except Exception as e:
            data = {'msg': e}
        return JsonResponse(data, safe=False, json_dumps_params={'ensure_ascii': False})


def get_apis(request):
    connection = pymysql.connect(host=config.host, user=config.user,
                                 password=config.password, db=config.db, port=config.port)
    if request.method == 'GET':
        try:
            cmd = "SELECT url,summary,method,query,body,response from testcase_api; "
            cursor = connection.cursor()
            cursor.execute(cmd)
            data = dictfetchall(cursor)
            print(data)
            cursor.close()
            connection.close()
        except Exception as e:
            data = {'status':'fail','msg': e}
        return JsonResponse(data, safe=False, json_dumps_params={'ensure_ascii': False})


def dictfetchall(cursor):
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns,json.loads(row) if '{' in row else row))
        for row in cursor.fetchall()
        ]

